package com.mtgdeckbuilder.server.dao;

import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.commons.lang.StringUtils;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.mtgdeckbuilder.server.EMF;
import com.mtgdeckbuilder.server.entity.Card;

/**
 * The Data Access Object for a card.
 * 
 * @author Nicolas Deslandes
 */
public class CardDAO extends DAO<Card> {

   private static Logger logger = Logger.getLogger(CardDAO.class.getName());

   @SuppressWarnings("unchecked")
   @Override
   public List<Card> query(final Card args) {
      logger.finest("Call of query(" + args + ")");
      final EntityManager em = EMF.get().createEntityManager();
      try {
         final StringBuilder jpqlQuery = new StringBuilder("select from " + Card.class.getName());
         if (!StringUtils.isEmpty(args.getName())) {
            jpqlQuery.append(" where nameInUpperCase = :nameInUpperCase ");
         }
         final Query query = em.createQuery(jpqlQuery.toString());
         if (!StringUtils.isEmpty(args.getNameInUpperCase())) {
            query.setParameter("nameInUpperCase", args.getNameInUpperCase());
         }

         final List<Card> cards = query.getResultList();
         cards.size();
         return cards;
      } finally {
         em.close();
      }
   }

   @Override
   public Card fetch(final long id) {
      logger.finest("Call of fetch(" + id + ")");
      final Key key = KeyFactory.createKey(Card.class.getSimpleName(), id);
      return fetch(key);
   }

   @Override
   public Card fetch(final Key key) {
      logger.finest("Call of fetch(" + key + ")");
      final EntityManager em = EMF.get().createEntityManager();
      try {
         return em.find(Card.class, key);
      } finally {
         em.close();
      }
   }

}
